package com.haoniu.common.utils.chatbot;

import com.haoniu.common.utils.JsonUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 钉钉消息推送
 * @author shilvfei
 */
public class ChatBotSend {

    private static String WEBHOOK_TOKEN =
            "https://oapi.dingtalk.com/robot/send?access_token=a2a51d7f513661adc0252f5176ad3066faf36f8d609e49f504c084f8262b3dbc";

    public static void sendDing(String content) throws IOException {
        // 文本内容
        Text text = new Text();
        text.setContent(content);

        // @所有人 或者 @指定账户
          //At at = new At();

        TextMsg textMsg = new TextMsg();
        textMsg.setText(text);
        String jsonText = JsonUtils.objectToJson(textMsg);
        sendContent(jsonText);
    }

    private static void sendContent(String content) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(content, "utf-8");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
        }
    }
}
